from django import forms
from .models import User


class BaseForm(forms.ModelForm):
    """
    基础表单校验类
    [
        [{'message': '密码为6-12位字符', 'code': 'min_length'}],
        [{'message': '手机号格式不符', 'code': 'invalid'}]
    ]
    """
    def get_form_error(self):
        errors = self.errors.get_json_data()
        new_errors = []
        for messages in errors.values():
            for message_dict in messages:
                new_errors.append(message_dict.get('message'))
        return new_errors


class SignupForm(BaseForm):
    """注册form表单"""
    password_repeat = forms.CharField(min_length=6, max_length=12)

    # TODO: 重写父类clean方法
    def clean(self):
        cleaned_data = super(SignupForm, self).clean()
        password = cleaned_data.get('password')
        password_repeat = cleaned_data.get('password_repeat')
        # 校验两次密码输入是否一致
        if password != password_repeat:
            raise forms.ValidationError('两次密码输入不一致')
        return cleaned_data

    class Meta:
        # 表单模型
        model = User
        # 排除create_time字段校验
        exclude = ['create_time']


class SigninForm(BaseForm):
    """登录form"""

    class Meta:
        model = User
        # 需要校验telphone、password字段
        fields = ['telphone', 'password']
        # TODO: 自定义错误消息
        error_messages = {
            'telphone': {
                'invalid': '手机号格式不符'
            },
            'password': {
                'min_length': '密码为6-12位字符',
                'max_length': '密码为6-12位字符',
            }
        }
